import 'package:campus_order/config/router_page_name.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_easylogger/flutter_logger.dart';

import '../../../models/category_model.dart';
import '../../../http/http_service.dart';

class OrderFoodLogic extends GetxController {
  // 分类列表
  final categories = <Category>[].obs;

  // 菜品列表
  final foods = <Food>[].obs;

  // 选中的分类索引
  final selectedCategoryIndex = 0.obs;

  // 购物车
  final cartItems = <CartItem>[].obs;

  // 总价
  final totalPrice = 0.0.obs;

  // 加载状态
  final isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    // 加载菜单数据
    loadMenuData();
  }

  // 加载菜单数据
  Future<void> loadMenuData() async {
    // 如果正在加载中，直接返回
    if (isLoading.value) return;

    isLoading.value = true;

    try {
      final response = await HttpService().get('/menu');
      final responseData = response.data;

      // 解析分类数据
      final List<dynamic> categoriesData = responseData['categories'];
      categories.clear();
      categories.addAll(categoriesData.map((data) => Category(
        id: data['id'],
        name: data['name'],
      )));

      // 解析菜品数据
      final List<dynamic> foodsData = responseData['foods'];
      foods.clear();
      foods.addAll(foodsData.map((data) => Food(
        id: data['id'],
        categoryId: data['categoryId'],
        name: data['name'],
        price: double.parse(data['price'].toString()),
        image: data['image'],
        description: data['description'] ?? '',
      )));

      Logger.i('菜单加载成功: ${categories.length}个分类, ${foods.length}个菜品');
    } catch (e) {
      Logger.e('菜单加载失败: $e');
      Get.snackbar(
        '加载失败',
        '菜单数据加载失败，请检查网络连接',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.white70,
        duration: Duration(seconds: 2),
      );
    } finally {
      isLoading.value = false;
    }
  }

  // 选择分类
  void selectCategory(int index) {
    selectedCategoryIndex.value = index;
  }

  // 获取当前分类下的菜品
  List<Food> getFoodsByCategory() {
    if (selectedCategoryIndex.value < 0 || selectedCategoryIndex.value >= categories.length) {
      return [];
    }

    final categoryId = categories[selectedCategoryIndex.value].id;
    return foods.where((food) => food.categoryId == categoryId).toList();
  }

  // 添加到购物车
  void addToCart(Food food) {
    // 检查是否已在购物车中
    final index = cartItems.indexWhere((item) => item.food.id == food.id);

    if (index >= 0) {
      // 已存在
      cartItems[index].quantity++;
      cartItems.refresh();
    } else {
      // 不存在，添加新项
      cartItems.add(CartItem(food: food, quantity: 1));
    }

    // 更新总价
    _updateTotalPrice();
  }

  // 从购物车减少
  void decreaseCartItem(Food food) {
    final index = cartItems.indexWhere((item) => item.food.id == food.id);

    if (index >= 0) {
      if (cartItems[index].quantity > 1) {
        // 数量大于1
        cartItems[index].quantity--;
        cartItems.refresh();
      } else {
        // 数量为1，移除
        cartItems.removeAt(index);
      }

      // 更新总价
      _updateTotalPrice();
    }
  }

  // 获取购物车中某个菜品的数量
  int getCartItemCount(int foodId) {
    final index = cartItems.indexWhere((item) => item.food.id == foodId);
    return index >= 0 ? cartItems[index].quantity : 0;
  }

  // 更新总价
  void _updateTotalPrice() {
    double total = 0;
    for (var item in cartItems) {
      total += item.food.price * item.quantity;
    }
    totalPrice.value = total;
  }

  // 显示购物车详情
  void showCartDetails() {
    if (cartItems.isEmpty) {
      Get.snackbar(
        '购物车为空',
        '请先添加商品到购物车',
        backgroundColor: Colors.white70,
        snackPosition: SnackPosition.TOP,
      );
      return;
    }

    final Color backgroundColor = Color(0xFFBE9650);

    Get.bottomSheet(
      Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('购物车', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                TextButton(
                  onPressed: () {
                    cartItems.clear();
                    _updateTotalPrice();
                    Get.back();
                  },
                  child: Text('清空'),
                ),
              ],
            ),
            Divider(),
            Obx(() => ListView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount: cartItems.length,
              itemBuilder: (context, index) {
                final item = cartItems[index];
                return ListTile(
                  title: Text(item.food.name),
                  subtitle: Text('¥${item.food.price.toStringAsFixed(2)}'),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: Icon(Icons.remove),
                        onPressed: () => decreaseCartItem(item.food),
                      ),
                      Text('${item.quantity}'),
                      IconButton(
                        icon: Icon(Icons.add),
                        onPressed: () => addToCart(item.food),
                      ),
                    ],
                  ),
                );
              },
            )),
            Divider(),
            Obx(() => Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '总计: ¥${totalPrice.value.toStringAsFixed(2)}',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                ),
                ElevatedButton(
                  onPressed: () {
                    Get.back();
                    submitOrder();
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: backgroundColor,
                  ),
                  child: Text('去结算', style: TextStyle(color: Colors.white)),
                ),
              ],
            )),
          ],
        ),
      ),
    );
  }

  // 提交订单
  void submitOrder() {
    if (cartItems.isEmpty) {
      Get.snackbar('购物车为空', '请先添加商品到购物车');
      return;
    }
    Get.toNamed(RouterPageName.confirmOrderPage, arguments: {
      'cartItems': cartItems,
      'totalPrice': totalPrice.value,
    });
  }
}